<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      />
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeStep" finish-status="success" align-center>
        <el-step title="基本信息"/>
        <el-step title="商品参数"/>
        <el-step title="商品属性"/>
        <el-step title="商品图片"/>
        <el-step title="商品内容"/>
        <el-step title="完成"/>
      </el-steps>
      <!-- 表单 -->
      <el-form
        :model="addGoodsForm"
        ref="addGoodsFormRef"
        :rules="rules"
        label-position="top"
      >
        <!-- 标签栏 -->
        <el-tabs tab-position="left" v-model="activeTab" :before-leave="changeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name" />
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"/>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"/>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"/>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="cates"
                :props="catesProps"
                v-model="addGoodsForm.goods_cat"
                @change="changeCates"
                clearable
              />
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(val,key) in item.attr_vals"
                  :key="key"
                  :label="val"
                  border
                />
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"/>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :headers="uploadHeader"
              list-type="picture"
              :on-preview="onPreviewPic"
              :before-remove="beforeRemovePic"
              :on-success="onUploadSuccess"
            >
              <el-button size="small" type="primary">点击上传图片</el-button>
              <el-alert
                slot="tip"
                title="只能上传 jpg/png 文件，大小不超过 500KB"
                type="info"
                class="upload-tip"
                show-icon
                :closable="false"
              />
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addGoodsForm.goods_introduce">
            </quill-editor>
            <el-button type="primary" @click="addGoods" class="btn-add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" width="80%"
      :visible.sync="previewDialogVisible"
    >
      <img :src="previewURL" width="100%" alt="图片加载失败"/>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  data () {
    const required = name => {
      return { required: true, message: `请输入${name}`, trigger: 'blur' }
    }
    const positiveValidator = (rules, value, callback) => {
      if (value > 0) {
        return callback() // 验证通过
      } else {
        return callback(new Error('请输入一个正数'))
      }
    }
    const positive = () => {
      return { validator: positiveValidator, trigger: 'blur' }
    }
    return {
      // 当前激活页签
      activeTab: '0',
      // 添加商品表单
      addGoodsForm: {
        goods_name: '',
        goods_price: 1,
        goods_weight: 1,
        goods_number: 1,
        goods_cat: [],
        pics: [], // 商品图片
        goods_introduce: '', // 商品内容富文本
        attrs: [] // 动态参数和静态属性
      },
      rules: {
        goods_name: [ required('商品名称') ],
        goods_price: [ required('商品价格'), positive() ],
        goods_weight: [ required('商品重量'), positive() ],
        goods_number: [ required('商品数量'), positive() ],
        goods_cat: [ required('商品分类') ]
      },
      // 分类列表
      cates: [],
      // 级联选择器配置对象
      catesProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 动态参数列表数据
      manyData: [],
      // 静态属性列表数据
      onlyData: [],
      // 上传图片 api
      uploadURL: 'http://localhost:8888/api/private/v1/upload',
      uploadHeader: { Authorization: window.sessionStorage.getItem('token') },
      previewURL: '',
      previewDialogVisible: false
    }
  },
  created () {
    this.getCates()
  },
  methods: {
    // 添加商品
    addGoods () {
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 拷贝 this.addGoodsForm，填充表单
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        form.attrs = []
        this.getParams('many')
        for (let item of this.manyData) {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        }
        this.getParams('only')
        for (let item of this.onlyData) {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        }
        // 发起请求
        const { data } = await this.$http.post('goods', form)
        if (data.meta.status !== 201) {
          return this.$message.error('添加商品失败，' + data.meta.msg)
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods') // 回到商品列表
      })
    },
    // 获取分类列表
    async getCates () {
      const { data } = await this.$http.get('categories')
      if (data.meta.status !== 200) {
        return this.$message.error('获取商品分类失败，' + data.meta.msg)
      }
      this.cates = data.data
    },
    // 获取商品参数
    async getParams (sel) {
      const { data } = await this.$http.get(`categories/${this.cateId}/attributes`, { params:
        { sel }
      })
      if (data.meta.status !== 200) {
        return this.$message.error('获取商品参数失败，' + data.meta.msg)
      }
      if (sel === 'many') {
        // 获取成功，先处理后赋值
        data.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyData = data.data
      } else if (sel === 'only') {
        this.onlyData = data.data
      }
    },
    // 级联选择器改变事件
    changeCates () {
      // 只允许选中三级分类
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // 标签页改变事件
    changeTab (to, from) {
      // console.log(from + ' -> ' + to)
      if (from === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false // 阻止标签页切换
      }
      if (to === '1') { // 动态参数面板
        this.getParams('many')
      } else if (to === '2') { // 静态属性面板
        this.getParams('only')
      }
    },
    // 上传图片成功事件
    onUploadSuccess (data) {
      if (data.meta.status !== 200) {
        return this.$message.error('上传图片失败，' + data.meta.msg)
      }
      const picInfo = { pic: data.data.tmp_path }
      this.addGoodsForm.pics.push(picInfo)
      // console.log(this.addGoodsForm.pics.map(x => x.pic))
    },
    // 移除图片事件
    beforeRemovePic (data) {
      const path = data.response.data.tmp_path
      const i = this.addGoodsForm.pics.findIndex(x => x.pic === path)
      if (i === -1) {
        this.$message.error('移除图片出错')
        return false
      }
      this.addGoodsForm.pics.splice(i, 1)
      // console.log(this.addGoodsForm.pics.map(x => x.pic))
    },
    // 预览图片事件
    onPreviewPic (data) {
      this.previewURL = data.response.data.url
      this.previewDialogVisible = true
    }
  },
  computed: {
    activeStep () {
      return parseInt(this.activeTab)
    },
    // 当前选中的三级分类 id
    cateId () {
      const len = this.addGoodsForm.goods_cat.length
      if (len === 3) {
        return this.addGoodsForm.goods_cat[len - 1]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.upload-tip,
.btn-add {
  margin-top: 15px;
}
</style>
